import { createRouter, createWebHistory } from 'vue-router';
// 动态导入组件
const Login = () => import('../views/Login.vue');
const Register = () => import('../views/Register.vue');
const AdminDashboard = () => import('../views/AdminDashboard.vue');
const BookAdminDashboard = () => import('../views/BookAdminDashboard.vue');
const UserDashboard = () => import('../views/UserDashboard.vue');
const NotFound = () => import('../views/NotFound.vue');
const Home = () => import('../views/Home.vue');
const BookDetail = () => import('../views/BookDetail.vue');
const NoticeDetail = () => import('../views/NoticeDetail.vue');
const NoticeList = () => import('../views/NoticeList.vue');
const BookList = () => import('../views/BookList.vue');

// 定义路由
const routes = [
  {
    path: '/',
    redirect: '/home',
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false },
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: { requiresAuth: false },
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: { requiresAuth: false },
  },
  {
    path: '/books',
    name: 'BookList',
    component: BookList,
    meta: { requiresAuth: false },
  },
  { path: '/book/:bookNumber',
    name: 'BookDetail',
    component: BookDetail,
  },
  {
    path: '/notices/:noticeId',
    name: 'NoticeDetail',
    component: NoticeDetail
  },
  {
    path: '/notices',
    name: 'NoticeList',
    component: NoticeList
  },
  {
    path: '/admin',
    name: 'AdminDashboard',
    component: AdminDashboard,
    meta: { requiresAuth: true, role: 'admin' },
  },
  {
    path: '/book-admin',
    name: 'BookAdminDashboard',
    component: BookAdminDashboard,
    meta: { requiresAuth: true, role: 'book_admin' },
  },
  {
    path: '/user-dashboard',
    name: 'UserDashboard',
    component: UserDashboard,
    meta: { requiresAuth: true, role: 'user' },
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFound,
    meta: { requiresAuth: false },
  },
];

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = !!localStorage.getItem('userType');
  const userType = localStorage.getItem('userType');

  if (to.meta.requiresAuth) {
    if (!isAuthenticated) {
      return next({ path: '/login' });
    }
    if (to.meta.role && to.meta.role !== userType) {
      return next({ path: '/404' });
    }
  }
  next();
  window.scrollTo(0, 0); // 滚动到页面顶部
});

export default router;
